<template>
  <BasicModal v-bind="$attrs" @register="register" :title="getTitle" width="1250px" @ok="affirmAllot">
    <div class="dClass">
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <a-button type="primary" size="large" style="width: 145px; height: 45px" :disabled="disabled"  @click="autoAllotTwo">
        <a-icon type="robot" />自动分配</a-button>
      <a-button type="primary" size="large" style="width: 145px; height: 45px" :disabled="disabled"  @click="handleUserModal">
        <a-icon type="user" />手动分配</a-button>
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    </div>
    <a-form ref="formRef" class="antd-modal-form">
      <div>
        <!--引用表格-->
        <BasicTable :key="tableKey" bordered size="middle" :loading="loading" :canResize="false"
          :columns="labItemsColumnsA" :dataSource="dataSource" :pagination="false">
          <!--操作栏-->
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'itemStatus'">
              <span>
                <a-tag
                  :color="record.itemStatus === '待分配' ? 'volcano' : record.itemStatus === '已分配' ? 'green' : 'geekblue'">
                  {{ record.itemStatus }}
                </a-tag>
              </span>
            </template>
            <template v-if="column.key === 'userName'">
              <div v-if="disabled">{{ record.userName }}</div>
              <div v-else>
                <!-- <span class="checkAduit" v-if="record.userName" :disabled="disabled" @click="handleUserBut(record.id)">{{ record.userName }}</span> -->
                <!-- <a-button v-else type="primary" size="small" @click="handleUserBut(record.id)" :disabled="disabled">待分配</a-button> -->
                <span class="checkAduit" v-if="record.userName" :disabled="disabled" @click="handleUserButTwo(record)">{{ record.userName }}</span>
                <a-button v-else type="primary" size="small" @click="handleUserButTwo(record)" :disabled="disabled">待分配</a-button>
              </div>
            </template>
            <template v-if="column.key === 'auditName'">
              <div v-if="disabled">{{ record.auditName }}</div>
              <div v-else>
                <span class="checkAduit" v-if="record.auditName" :disabled="disabled" @click="selectAudit(record)">{{record.auditName }}</span>
                <a-button v-else type="primary" size="small" @click="selectAudit(record)" :disabled="disabled">选择复核人</a-button>
              </div>
            </template>
            <template v-else-if="column.key === 'finDate'">
              <a-date-picker valueFormat="YYYY-MM-DD" v-model:value="record.finDate" style="width: 100%; height: 100%" :disabled="disabled" />
            </template>
          </template>

          <template #fileSlot="{ text }">
            <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
            <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small"
              @click="downloadFile(text)">下载</a-button>
          </template>
        </BasicTable>
        <a-row v-model:value="dataSource2" style="margin-top: 10px; width: 100%">
          <a-col :span="2">
            <a-form-item label="委托单位" name="entName">
              <a-input v-model:value="dataSource2.entName" :disabled="true" style="width: 200px"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="报告类型" name="entrustType">
              <a-input v-model:value="dataSource2.entrustType" :disabled="true" style="width: 100px"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="样品大类" name="sampleType">
              <a-input v-model:value="dataSource2.sampleType" :disabled="true" style="width: 150px"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="样品类别" name="sampleSort">
              <a-input v-model:value="dataSource2.sampleSort" :disabled="true" style="width: 120px"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="主检人" name="editorChief" style="width: 200px">
              <div v-if="disabled">
                <div style="display: inline-block; width: 80px">{{ dataSource2.editorChief }}</div>
              </div>
              <div v-else>
                <div class="checkAduit" v-if="dataSource2.editorChief" style="display: inline-block; width: 80px"
                  @click="handleUserBut2(dataSource2.id)">{{ dataSource2.editorChief }}</div>
                <a-button type="primary" v-else size="small" @click="handleUserBut2(dataSource2.id)"
                  :disabled="disabled">待选择</a-button>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </div>
    </a-form>
  </BasicModal>
  <!-- 实验任务分配区域 -->
  <TableUserModal @register="registerUserModal" @getSelectResult="onSelectOk" @getSelectUser="onUserOk"
    @selectAuditConfirm="selectAuditConfirm" @selectAuditConfirm2="selectAuditConfirm2"></TableUserModal>

    <TableUserSkillModal @register="registerUserSkillModal" @getSelectUserSkill="onSelectOkTwo"></TableUserSkillModal>
    <TableUserSkillModalB @register="registerUserSkillModalB" @getSelectUserSkillB="onSelectOkTwoB"></TableUserSkillModalB>
</template>

<script lang="ts" setup>
import { BasicModal, useModalInner } from '/@/components/Modal';
import { ref, reactive } from 'vue';
import { submitAllot, queryItemsById, autoAllotUser, autoUserSkill } from './LabEntrustAllotList.api';
import { labItemsColumnsA } from './LabEntrustAllotList.data';
import { downloadFile } from '/@/utils/common/renderUtils';
import { BasicTable } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import TableUserModal from './LabEntrustAllotUserTable.vue';
import TableUserSkillModal from './LabItemUserSkillTableA.vue';
import TableUserSkillModalB from './LabItemUserSkillTableB.vue';
import { Modal } from 'ant-design-vue';
import moment from 'moment';

const loading = ref(false);
const disabled = ref(false);
const dataSource = ref([
  {
    id: '',
    createBy: '',
    createTime: '',
    updateBy: '',
    updateTime: '',
    sysOrgCode: '',
    itemId: '',
    itemName: '',
    basisName: '',
    basisNum: '',
    basisScope: '',
    basisAtta: '',
    bigTypeId: '',
    bigTypeName: '',
    midTypeId: '',
    midTypeName: '',
    team: '',
    entrustId: '',
    userName: '',
    userId: '',
    itemStatus: '',
    itemFinishTime: '',
    remark: '',
    auditId: '',
    auditName: '',
    samId: '',
    samName: '',
    samNum: '',
    finDate: '',
    pubDate: '',
  },
]);
const dataSource2 = ref({
  id: '',
  entName: '',
  entrustType: '',
  sampleType: '',
  sampleSort: '',
  editorChief: '',
  editorChiefId: '',
});
const emit = defineEmits(['success']);
const tableKey = ref('table1');
const getTitle = ref('实验任务分配');
const formData = reactive({
  id: '',
  entrustType: '',
  labEntrustItems: [
    {
      id: '',
      createBy: '',
      createTime: '',
      updateBy: '',
      updateTime: '',
      sysOrgCode: '',
      itemId: '',
      itemName: '',
      basisName: '',
      basisNum: '',
      basisScope: '',
      basisAtta: '',
      bigTypeId: '',
      bigTypeName: '',
      midTypeId: '',
      midTypeName: '',
      team: '',
      entrustId: '',
      userName: '',
      userId: '',
      itemStatus: '',
      itemFinishTime: '',
      remark: '',
      auditId: '',
      auditName: '',
      samId: '',
      samName: '',
      samNum: '',
      finDate: '',
      pubDate: '',
    },
  ],
  editorChief: '',
  editorChiefId: '',
});

const finDate = moment(moment().add(15, 'days').toDate()).format('YYYY-MM-DD');
const pubDate = moment(moment().toDate()).format('YYYY-MM-DD');

const formItemData = reactive({
  itemId: '',
});
const [register, { setModalProps, closeModal }] = useModalInner((data) => {
  setModalProps({
    minHeight: 150,
    showOkBtn: data.isUpdate,
  });
  disabled.value = data.disabled;
  dataSource.value = [];
  dataSource2.value = {
    id: '',
    entName: '',
    entrustType: '',
    sampleType: '',
    sampleSort: '',
    editorChief: '',
    editorChiefId: '',
  };
  if (!disabled.value) {
    data.record.editorChief = '';
    data.record.editorChiefId = '';
  }
  loading.value = true;
  let id = data.record.id;
  formData.id = id;
  formData.entrustType = data.record.entrustType;
  queryItemsById({ id })
    .then((res) => {
      if (res.success) {
        dataSource.value = res.result.records;
        dataSource2.value = data.record;
        if (!disabled.value) {
          for (let i = 0; i < dataSource.value.length; i++) {
            dataSource.value[i].finDate = finDate;
            dataSource.value[i].pubDate = pubDate;
          }
        }
      }
    })
    .finally(() => {
      loading.value = false;
    });
});

async function affirmAllot() {
  Modal.confirm({
    title: '是否确认分配?',
    async onOk() {
      formData.labEntrustItems = dataSource.value;
      formData.editorChief = dataSource2.value.editorChief;
      formData.editorChiefId = dataSource2.value.editorChiefId;
      await submitAllot(formData);
      closeModal();
      emit('success');
    },
    onCancel() {
      console.log('取消分配');
    },
  });
}

//注册model
const [registerUserModal, { openModal: openUserModal }] = useModal();
const [registerUserSkillModal, { openModal: openUserTowModal }] = useModal();
const [registerUserSkillModalB, { openModal: openUserTowModalB }] = useModal();

function handleUserModal() {
  let mId = formData.id;
  openUserModal(true, {
    mId,
    type: 'all',
  });
}

function handleUserBut(id) {
  let mId = formData.id;
  openUserModal(true, {
    mId,
    type: 'sin',
  });
  formItemData.itemId = id;
}

function handleUserBut2(id) {
  let mId = formData.id;
  openUserModal(true, {
    mId,
    type: 'sin',
    flag: 'min',
  });
  formItemData.itemId = id;
}

function onUserOk(uId, uName) {
  dataSource.value.forEach((item) => {
    if (formItemData.itemId == item.id) {
      item.userId = uId;
      item.userName = uName;
    }
  });
  if (tableKey.value == 'table1') {
    tableKey.value = 'table2';
  } else {
    tableKey.value = 'table1';
  }
}

function onSelectOk(uId, uName) {
  dataSource.value.forEach((item) => {
    item.userId = uId;
    item.userName = uName;
  });
  if (tableKey.value == 'table1') {
    tableKey.value = 'table2';
  } else {
    tableKey.value = 'table1';
  }
}

function handleUserButTwo(record) {
  openUserTowModal(true, {
    itemId:record.itemId,
    basisId:record.basisId
  });
  formItemData.itemId = record.id;
}



function onSelectOkTwo(uId, uName) {

  dataSource.value.forEach((item) => {
    if (formItemData.itemId == item.id) {
      item.userId = uId;
      item.userName = uName;
    }
  });
  if (tableKey.value == 'table1') {
    tableKey.value = 'table2';
  } else {
    tableKey.value = 'table1';
  }
}

function onSelectOkTwoB(uId, uName) {

dataSource.value.forEach((item) => {
  if (formItemData.itemId == item.id) {
    item.auditId = uId;
    item.auditName = uName;
  }
});
if (tableKey.value == 'table1') {
  tableKey.value = 'table2';
} else {
  tableKey.value = 'table1';
}
}

//原自动分配的方法（1）
// async function autoAllot() {
//   let mId = formData.id;
//   const user = await autoAllotUser({ mId });
//   let userId = user.id;
//   let realname = user.realname;
//   dataSource.value.forEach((item) => {
//     item.userId = userId;
//     item.userName = realname;
//   });
//   if (tableKey.value == 'table1') {
//     tableKey.value = 'table2';
//   } else {
//     tableKey.value = 'table1';
//   }
// }
//原自动分配的方法（2）
async function autoAllotTwo() {
  let mId = formData.id;
  const itemUsers = await autoUserSkill({ mId });
  dataSource.value.forEach((item) => {
    const itemIdA = item.itemId;
    itemUsers.forEach((user) => {
      const itemIdB = user.itemId;
      if (itemIdA == itemIdB) {
        item.userId = user.userId;
        item.userName = user.userName;
      }
    })
  });
   if (tableKey.value == 'table1') {
     tableKey.value = 'table2';
   } else {
     tableKey.value = 'table1';
   }
}



// 选择复核人员
function selectAudit(record) {
  openUserTowModalB(true, {
    itemId:record.itemId,
    basisId:record.basisId
  });
  formItemData.itemId = record.id;
}

// 选择复核人员弹窗回调
function selectAuditConfirm(uId, uName) {
  dataSource.value.forEach((item) => {
    if (formItemData.itemId == item.id) {
      item.auditId = uId;
      item.auditName = uName;
    }
  });
  if (tableKey.value == 'table1') {
    tableKey.value = 'table2';
  } else {
    tableKey.value = 'table1';
  }
}
// 选择复核人员弹窗回调
function selectAuditConfirm2(uId, uName) {
  dataSource2.value.editorChief = uName;
  dataSource2.value.editorChiefId = uId;
}
</script>

<style scoped>
.dClass {
  display: flex;
  justify-content: space-between;
  /* 使两个按钮在div中水平对齐并分开 */
}

.ant-modal {
  width: 85% !important;
}

.checkAduit {
  color: #009688;
  cursor: pointer;
}
</style>
